import { Assets, Sprite } from "pixi.js";
import { PixijsRender } from "../PixijsRender";
import { BaseEntity } from "./BaseEntity";
import { ViewState } from "./PixijsEntities";

export class SpriteEntity extends BaseEntity {

    constructor(pixiRender: PixijsRender) {
        super(pixiRender);
        this.view = new Sprite();
        //this.__render.viewRoot.addChild(this.view);
        this.className = this.constructor.name
    }

    loadAssets(){
        this.__render.world.update(this, "viewState", ViewState.Loading)
        let url = this.url;
        if(!url.startsWith("http")) {
            url = this.__render.resRootUrl + url;
        }
        Assets.load(url).then((texture) => {
            if (this.viewState === ViewState.Loading) {
                (this.view as Sprite).texture = texture;
                this.size.width = texture.width;
                this.size.height = texture.height;
                this.__render.world.update(this, "viewState", ViewState.Showing)
                
            }
            this.__render.viewDirty = true;
        }).catch(e => {
            console.error(e);
        })
        
    }

    applyData(data: any){
        let needReload = false;
        if(data && data.url){
            needReload = true;
        }
        super.applyData(data);
        if(needReload){
            this.loadAssets();
        }
    }
}